package com.borqsprocessmanager.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.WifiManager;

import com.borqsprocessmanager.App;
import com.borqsprocessmanager.BatteryManagerService;
import com.borqsprocessmanager.info.BatteryTaskInfo;
import com.borqsprocessmanager.interfaces.INetStateChanged;
import com.borqsprocessmanager.util.Log;

public class ConnectionChangeReceiver extends BroadcastReceiver {
	private final String TAG = "ConnectionChangeReceiver";

	private WifiManager mWifiManager;
	private boolean isWifiConnactiv = false;
	private boolean isMobileConnactiv = false;

	public ConnectionChangeReceiver(BatteryManagerService service) {
		mWifiManager = (WifiManager) App.mContext
				.getSystemService(Context.WIFI_SERVICE);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		Log.v(TAG, "网络状态改变");

		// 获得网络连接服务
		ConnectivityManager connManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		// State state = connManager.getActiveNetworkInfo().getState();
		// 获取WIFI网络连接状态
		State state = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();

		Log.v(TAG, "WIFI===" + state);
		// 判断是否正在使用WIFI网络
		if (State.CONNECTED == state) {
			isWifiConnactiv = true;
		} else {
			isWifiConnactiv = false;
		}
		// 获取GPRS网络连接状态
		NetworkInfo network = connManager
				.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
		if (network != null) {
			state = network.getState();
			// 判断是否正在使用GPRS网络
			Log.v(TAG, "GPRS===" + state);
			if (State.CONNECTED == state) {
				isMobileConnactiv = true;
			} else {
				isMobileConnactiv = false;
			}
		}
	}

	public int getNetWorkState() {
		int wifistate = 0;
		wifistate = mWifiManager.getWifiState();
		if (isWifiConnactiv) {
			return BatteryTaskInfo.WIFI;
		}
		if (isMobileConnactiv) {
			if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
				Log.v(TAG, " WIFI_MOBILE");
				return BatteryTaskInfo.WIFI_MOBILE;
			} else {
				Log.v(TAG, " MOBILE");
				return BatteryTaskInfo.MOBILE;
			}
		}
		if (wifistate == WifiManager.WIFI_STATE_ENABLED) {
			Log.v(TAG, " WIFI_NORMAL");
			return BatteryTaskInfo.WIFI_NORMAL;
		} else {
			Log.v(TAG, " NORMAL");
			return BatteryTaskInfo.NORMAL;
		}
	}
}
